package com.example.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * 全局异常
 */
@ControllerAdvice
public class GlobalException {
    private Logger logger = LoggerFactory.getLogger(GlobalException.class);
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultException(HttpServletRequest request,Exception e) throws  Exception{
        logger.error("",e);
        Result result = new Result();
        result.setMessage(e.getMessage());
        if(e instanceof org.springframework.web.servlet.NoHandlerFoundException){
            result.setCode(404);
        }
        else{
            result.setCode(500);
        }
        result.setData(null);
        result.setStatus(false);
        return result;
    }
}
